package com.uniledger.exchange.login;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.MenuItem;
import android.widget.Button;

import com.orhanobut.logger.Logger;
import com.uniledger.exchange.R;
import com.uniledger.exchange.UniApp;
import com.uniledger.exchange.base.activity.BaseActivity;
import com.uniledger.exchange.login.fragment.SignUpListener;
import com.uniledger.exchange.login.fragment.SignUpOneFragment;
import com.uniledger.exchange.login.fragment.SignUpThreeFragment;
import com.uniledger.exchange.login.fragment.SignUpTwoFragment;
import com.uniledger.exchange.model.OkSingleton;
import com.uniledger.exchange.model.rx.RxException;
import com.uniledger.exchange.stellar.TrustIntentService;
import com.uniledger.exchange.wallet.MnemonicActivity;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindString;
import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.internal.operators.completable.CompletableFromAction;
import io.reactivex.schedulers.Schedulers;

/**
 * 注册页面
 */
public class SignUpActivity extends BaseActivity implements SignUpListener {

    @BindView(R.id.btn_sign_up)
    Button signUp;
    Admin admin;

    LoadingDialog dialog;
    @BindString(R.string.sign_up_bar_title)
    public String title;

    public static void start(Activity activity) {
        Intent intent = new Intent(activity, SignUpActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);
        dialog = new LoadingDialog(this);
        dialog.setLoadStyle(LoadingDialog.STYLE_LINE);
        dialog.setLoadingText(getResources().getString(R.string.loading));
        dialog.closeFailedAnim();
        dialog.closeSuccessAnim();
    }

    @Override
    public void initBar() {
        super.initBar();
        toolbar.setTitle(title);
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.btn_close_normal);
    }

    @Override
    public void getParams() {
        replaceFragment(SignUpOneFragment.newInstance("", ""), "step1");
    }

    private void replaceFragment(Fragment fragment, String name) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack so the user can navigate back
        transaction.replace(R.id.container_layout, fragment);
        transaction.addToBackStack(name);
        // Commit the transaction
        transaction.commit();
    }

    @Override
    public void getName(String first, String last) {
        admin = new Admin(first, last);
        replaceFragment(SignUpTwoFragment.newInstance(admin, ""), "step2");
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.btn_back_selector);
    }

    @Override
    public void getMobile(Admin admin) {
        //TODO 请求短信验证码
        String tel = replaceBlank(admin.mobile);
//        Api.getService().getCaptcha(tel)
//                .compose(io_main())
//                .compose(RxProgress.applyProgressBar(this))
//                .subscribe(new Consumer<HttpResult>() {
//                    @Override
//                    public void accept(HttpResult httpResult) throws Exception {
//                        replaceFragment(SignUpThreeFragment.newInstance(admin, ""), "step3");
//                    }
//                }, new RxException<>(new Consumer<Throwable>() {
//                    @Override
//                    public void accept(Throwable throwable) throws Exception {
//                        replaceFragment(SignUpThreeFragment.newInstance(admin, ""), "step3");
//                    }
//                }));
        replaceFragment(SignUpThreeFragment.newInstance(admin, ""), "step3");
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.btn_back_selector);

    }

    @Override
    public void success(Admin admin) {

        //TODO 启动信任链
        TrustIntentService.start(this, admin);

        //TODO 注册成功
        new CompletableFromAction(new Action() {
            @Override
            public void run() throws Exception {
                UniApp.getDb().keyDao().insert(admin.walletKey);
                UniApp.getDb().adminDao().insert(admin);
                OkSingleton.getInstance().setToken(admin.token);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action() {
                    @Override
                    public void run() throws Exception {
                        dialog().close();
                        // TODO 结束注册
                        MnemonicActivity.start(SignUpActivity.this, admin.walletKey);
                        finish();
                    }
                }, new RxException<>(new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //TODO 结束注册
                        Logger.d(throwable.getMessage());
                        dialog().close();
                    }
                }));
    }

    @Override
    public void press(Uri uri) {

    }

    @Override
    public Button getButton() {
        return signUp;
    }

    @Override
    public void onBackPressed() {
        FragmentManager manager = getSupportFragmentManager();
        int count = manager.getBackStackEntryCount();

        if (count == 1) {
            finish();
        } else {
            if (count==2){
                getSupportActionBar().setHomeAsUpIndicator(R.drawable.btn_close_normal);
            }else {
                getSupportActionBar().setHomeAsUpIndicator(R.drawable.btn_back_selector);
            }
            super.onBackPressed();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    protected String replaceBlank(String str) {
        String dest = null;
        if (str == null) {
            return dest;
        } else {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
            return dest;
        }
    }

    @Override
    public LoadingDialog dialog() {
        return dialog;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dialog().close();
    }
}
